<template>
  <div class="app-container">
    <!-- 步骤条 -->
    <el-steps :active="activeStep" finish-status="success" align-center>
      <el-step title="选择结算记录"></el-step>
      <el-step title="上传发票/支付"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <!-- 第一步：选择结算记录 -->
    <div v-if="activeStep === 0">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="结算编码" prop="settlementCode">
          <el-input
            v-model="queryParams.settlementCode"
            placeholder="请输入结算编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合作方编码" prop="partnerCode" label-width="120px">
          <el-input
            v-model="queryParams.partnerCode"
            placeholder="请输入合作方编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="结算方式" prop="settlementMethod">
          <el-select v-model="queryParams.settlementMethod" placeholder="请选择结算方式" clearable>
            <el-option
              v-for="dict in settlement_ways"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange" :single-select="true">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="结算编码" align="center" prop="settlementCode" />
        <el-table-column label="合作方编码" align="center" prop="partnerCode" />
        <el-table-column label="合作方类型" align="center" prop="partnerType" />
        <el-table-column label="结算总金额" align="right" prop="settlementAmount" />
        <el-table-column label="货币单位" align="center" prop="currencyUnit" />
        <!-- <el-table-column label="结算方式" align="center" prop="settlementMethod">
          <template #default="scope">
            <dict-tag :options="settlement_ways" :value="scope.row.settlementMethod"/>
          </template>
        </el-table-column> -->
        <el-table-column label="协议编码" align="center" prop="agreementCode" />
        <el-table-column label="创建日期" align="center" prop="startDate">
         <template #default="scope">
           <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
         </el-table-column>
        
        <el-table-column label="实际支付日期" align="center" prop="paymentDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算状态" align="center" prop="settlementStatus">
        <template #default="scope">
          <el-tag :type="primary" disable-transitions>
            {{ scope.row.settlementStatus }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column label="备注信息" align="center" prop="remark" />
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page="queryParams.pageNum"
        :limit="queryParams.pageSize"
        @pagination="handlePagination"
      />

      <!-- 下一步按钮 -->
      <el-button type="primary" @click="nextStep" :disabled="!canProceedToNextStep">下一步</el-button>
    </div>

    <!-- 第二步：上传发票/支付 -->
    <div v-if="activeStep === 1">
      <div v-if="isDealer">
        <!-- 上传发票 -->
        <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :action="uploadAction"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :auto-upload="true"
          :drag="true"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
        </el-upload>
      </div>
      <div v-else>
        <!-- 支付表单 -->
        <el-form ref="paymentRef" :model="paymentForm" :rules="paymentRules" label-width="100px">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="paymentForm.paymentMethod" placeholder="请选择支付方式">
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信" value="wechat" />
              <el-option label="银联" value="unionpay" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="paymentForm.paymentAmount" placeholder="请输入支付金额" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="paymentForm.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </div>
      <el-button @click="prevStep">上一步</el-button>
      <el-button type="primary" @click="nextStep">下一步</el-button>
      
    </div>

    <!-- 第三步：完成 -->
    <div v-if="activeStep === 2">
      <el-result icon="success" title="操作成功" sub-title="您的操作已完成">
        <template #extra>
          <el-button type="primary" @click="resetForm">重新开始</el-button>
        </template>
      </el-result>
    </div>

    <!-- 二维码弹窗 -->
    <el-dialog v-model="showQrCode" title="支付二维码" width="30%">
      <div style="text-align: center;">
        <img :src="qrCodeUrl" alt="支付二维码" style="width: 200px; height: 200px;" />
        <p>请使用手机扫描二维码完成支付</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handlePaymentSuccess">支付完成</el-button>
        <el-button @click="closeQrCodeDialog">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listRecord, updateRecordStatus } from "@/api/settled/record";
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import QRCode from 'qrcode';

const { proxy } = getCurrentInstance();
const { settlement_ways } = proxy.useDict('settlement_ways');

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const selectedRecord = ref(null);
const total = ref(0);
const title = ref("");
const activeStep = ref(0);
const canProceedToNextStep = ref(false);
const isDealer = ref(false);
const fileList = ref([]);
const uploadAction = ref('https://your-real-upload-api.com/upload'); // 替换为真实的上传接口
const paymentForm = ref({
  paymentMethod: '',
  paymentAmount: '',
  remark: ''
});
const paymentRules = ref({
  paymentMethod: [
    { required: true, message: "支付方式不能为空", trigger: "change" }
  ],
  paymentAmount: [
    { required: true, message: "支付金额不能为空", trigger: "blur" }
  ],
  remark: [
    { required: true, message: "备注信息不能为空", trigger: "blur" }
  ],
});
const qrCodeUrl = ref('');
const showQrCode = ref(false);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    settlementCode: null,
    partnerCode: null,
    settlementMethod: null,
    settlementStatus: null,
  },
  settlementForm: {
    partnerCode: '',
    settlementAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    settlementStatus: '',
    remark: ''
  },
  settlementRules: {
    settlementMethod: [
      { required: true, message: "结算方式不能为空", trigger: "blur" }
    ],
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
    currencyUnit: [
      { required: true, message: "货币单位不能为空", trigger: "blur" }
    ],
    settlementStatus: [
      { required: true, message: "结算状态不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注信息不能为空", trigger: "blur" }
    ],
  },
  settlementDetailList: [] // 初始化为空数组
});

const { queryParams, settlementForm, settlementRules, settlementDetailList } = toRefs(data);

/** 查询结算记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows.map(row => ({
      ...row,
      partnerType: getPartnerType(row.partnerCode)
    })).sort((a, b) => {
      // 将 startDate 转换为 Date 对象进行比较
      return new Date(b.startDate) - new Date(a.startDate);
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  settlementForm.value = {
    partnerCode: '',
    settlementAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    taxRate: 0,
    taxAmount: 0,
    settlementStatus: '',
    remark: ''
  };
  settlementDetailList.value = [];
  activeStep.value = 0;
  canProceedToNextStep.value = false;
  isDealer.value = false;
  fileList.value = [];
  paymentForm.value = {
    paymentMethod: '',
    paymentAmount: '',
    remark: ''
  };
  proxy.resetForm("queryRef"); // 重置查询表单
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRecord.value = selection.length > 0 ? selection[0] : null;
  canProceedToNextStep.value = selection.length > 0;
  if (selection.length > 0) {
    const partnerCode = selection[0].partnerCode;
    isDealer.value = partnerCode === 'DEALER001'; // 假设经销商的编码为 'DEALER001'
    settlementForm.value.partnerCode = partnerCode;
    settlementForm.value.settlementAmount = selection[0].settlementAmount;
    settlementForm.value.settlementMethod = selection[0].settlementMethod;
    settlementForm.value.agreementCode = selection[0].agreementCode;
    settlementForm.value.currencyUnit = selection[0].currencyUnit;
    settlementForm.value.remark = selection[0].remark;

    // 设置支付金额为结算总金额
    paymentForm.value.paymentAmount = selection[0].settlementAmount;

    // 检查结算单的状态
    if (selection[0].settlementStatus === '待确认') {
      canProceedToNextStep.value = false;
      ElMessage.error('该结算单的状态是“待确认”，无法进行下一步操作');
    } else if (selection[0].settlementStatus === '待支付') {
      canProceedToNextStep.value = true;
    } else {
      canProceedToNextStep.value = false;
      ElMessage.error('该结算单的状态不允许进行下一步操作');
    }
  } else {
    canProceedToNextStep.value = false;
    paymentForm.value.paymentAmount = ''; // 清空支付金额
  }
}

/** 下一步 */
function nextStep() {
  if (activeStep.value === 0) {
    if (!canProceedToNextStep.value) {
      ElMessage.error('请先选择结算记录');
      return;
    }
  } else if (activeStep.value === 1) {
    if (isDealer.value) {
      if (fileList.value.length === 0) {
        ElMessage.error('请先上传发票');
        return;
      }
      // 更新结算状态为“已上传发票”
      updateRecordStatus(selectedRecord.value.settlementCode, '已上传发票').then(() => {
        ElMessage.success('结算状态更新为“已上传发票”');
        activeStep.value++;
      }).catch(error => {
        ElMessage.error('结算状态更新失败');
      });
    } else {
      proxy.$refs["paymentRef"].validate(valid => {
        if (!valid) return;

        // 根据支付方式生成二维码
        const paymentMethod = paymentForm.value.paymentMethod;
        if (paymentMethod === 'alipay') {
          generateAlipayQrCode();
        } else if (paymentMethod === 'wechat') {
          generateWechatQrCode();
        } else {
          ElMessage.error('暂不支持该支付方式');
          return;
        }

        // 显示二维码弹窗
        showQrCode.value = true;
      });
    }
    return; // 阻止默认的 activeStep.value++ 操作
  }
  if (activeStep.value < 2) {
    activeStep.value++;
  }
}

/** 上一步 */
function prevStep() {
  if (activeStep.value > 0) {
    activeStep.value--;
  }
}

// 生成支付宝二维码
function generateAlipayQrCode() {
  const paymentUrl = `https://example.com/alipay?amount=${paymentForm.value.paymentAmount}&outTradeNo=${selectedRecord.value.settlementCode}`;
  QRCode.toDataURL(paymentUrl)
    .then(url => {
      qrCodeUrl.value = url;
    })
    .catch(err => {
      ElMessage.error('生成支付宝二维码失败');
      console.error(err);
    });
}

// 生成微信二维码
function generateWechatQrCode() {
  const paymentUrl = `https://example.com/wechat?amount=${paymentForm.value.paymentAmount}&outTradeNo=${selectedRecord.value.settlementCode}`;
  QRCode.toDataURL(paymentUrl)
    .then(url => {
      qrCodeUrl.value = url;
    })
    .catch(err => {
      ElMessage.error('生成微信二维码失败');
      console.error(err);
    });
}
function handlePaymentSuccess() {
  // 更新结算状态为“已支付”
  updateRecordStatus(selectedRecord.value.settlementCode, '已支付').then(() => {
    ElMessage.success('结算状态更新为“已支付”');
    showQrCode.value = false;
    activeStep.value++;
  }).catch(error => {
    ElMessage.error('结算状态更新失败');
  });
}

function handleUploadSuccess(response, file) {
  ElMessage.success('文件上传成功');
  fileList.value.push(file);
}

function handleUploadError(err, file) {
  ElMessage.error('文件上传失败');
}

function beforeUpload(file) {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传文件只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传文件大小不能超过 2MB!');
    return false;
  }
  return true;
}

/** 根据合作方编码获取合作方类型 */
function getPartnerType(partnerCode) {
  if (partnerCode.startsWith('DEALER')) {
    return '经销商';
  } else if (partnerCode.startsWith('LEADER')) {
    return '团长';
  }else if (partnerCode.startsWith('BLOGGER')) {
    return '博主';
  }else if (partnerCode.startsWith('LOGISITICS')) {
    return '物流商';
  }else if (partnerCode.startsWith('SUPPLY')) {
    return '供货商';
  }else if (partnerCode.startsWith('S')) {
      return '供货商';
  }else if (partnerCode.startsWith('1')) {
      return '经销商';
  }else if (partnerCode.startsWith('2')) {
      return '经销商';
  }else if (partnerCode.startsWith('3')) {
      return '经销商';
  }else if (partnerCode.startsWith('4')) {
      return '经销商';
  }else {
    return '未知类型';
  }
}

function parseTime(time, format) {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return format.replace('{y}', year)
              .replace('{m}', month)
              .replace('{d}', day)
              .replace('{h}', hours)
              .replace('{i}', minutes)
              .replace('{s}', seconds);
}

function handlePagination({ page, limit }) {
  queryParams.pageNum = page;
  queryParams.pageSize = limit;
  getList();
}

function resetForm() {
  reset();
  activeStep.value = 0;
  ElMessage.success('已重置所有数据，可以重新开始操作');
}

function closeQrCodeDialog() {
  showQrCode.value = false;
  activeStep.value = 1;
}

getList(); // 初始化加载数据
</script>